import { Injectable } from '@nestjs/common';
import { Imgd_Enum_TypeKeys_Dto, Imgd_Create_Dto, Imgd_Update_Dto } from './assets/imgd.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Imgd } from './assets/imgd.entity';
import { Repository } from 'typeorm';
import { Imgd_Find_Dto } from './assets/imgd.dto';
import {
  util_Db_Add,
  util_Db_PageList,
  util_Db_Delete,
  util_Db_NoPageList,
  util_Db_Update,
} from '@/common/util/db';
import { Constant_Enum_Enum_Imgd_Enum_TypeKey } from '@/common/constants/enum';

@Injectable()
export class Imgd_Service {
  constructor(
    @InjectRepository(Imgd)
    private imgd_Repository: Repository<Imgd>,
  ) {}

  async imgd_Create(body: Imgd_Create_Dto) {
    return await util_Db_Add({
      createDto: body,
      repository: this.imgd_Repository,
    });
  }

  async imgd_FindByPage(query: Imgd_Find_Dto) {
    const { size, page } = query;
    return await util_Db_PageList<Imgd>({
      queryBuilder: this.imgd_Repository.createQueryBuilder('imgd').orderBy('imgd.order', 'ASC'),
      query: { 'imgd.typeKey': query.typeKey, size, page },
    });
  }

  async imgd_FindAll(query: Imgd_Find_Dto) {
    return await util_Db_NoPageList({
      queryBuilder: this.imgd_Repository.createQueryBuilder('imgd').orderBy('imgd.order', 'ASC'),
      query,
    });
  }

  async imgd_FindOneById(id: number) {
    return await this.imgd_Repository
      .createQueryBuilder('imgd')
      .andWhere(`imgd.id = :id`, { id: id })
      .getOne();
  }

  async imgd_FindByTypeKeys(query: Imgd_Enum_TypeKeys_Dto) {
    const queryList = query.typeKeys.split(',');
    const enumValues = Object.values(Constant_Enum_Enum_Imgd_Enum_TypeKey);
    const isValid = queryList.every((key) =>
      enumValues.includes(key as Constant_Enum_Enum_Imgd_Enum_TypeKey),
    );
    if (!isValid) {
      throw new Error('查询参数包含无效的图像类型键');
    }
    return await this.imgd_Repository
      .createQueryBuilder('imgd')
      .andWhere(`imgd.typeKey IN (:...typeKeys)`, { typeKeys: queryList })
      .getMany();
  }

  async imgd_Update(body: Imgd_Update_Dto) {
    return await util_Db_Update({
      findOne: () => this.imgd_FindOneById(body.id),
      updateDto: body,
      repository: this.imgd_Repository,
    });
  }

  async imgd_Remove(id: number) {
    return await util_Db_Delete({
      findOne: () => this.imgd_FindOneById(id),
      id,
      repository: this.imgd_Repository,
    });
  }
}
